package common.validation;

import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * Created by aceyin on 15/6/19.
 */
public class Validators {

    /**
     * Validate a java bean.
     *
     * @param o
     */
    public static ValidationResult validate(Object o) {
        Validator validator = getValidator();
        Set<ConstraintViolation<Object>> violations = validator.validate(o);

        return getValidationResult(violations);
    }

    /**
     * Validate one property of a bean.
     *
     * @param o
     * @param fieldName
     * @return
     */
    public static ValidationResult validate(Object o, String fieldName) {
        if (StringUtils.isBlank(fieldName)) {
            return new ValidationResult(false, "{validation.field.name.is.blank}");
        }
        Validator validator = getValidator();
        Set<ConstraintViolation<Object>> violations = validator.validateProperty(o, fieldName);
        return getValidationResult(violations);
    }

    private static ValidationResult getValidationResult(Set<ConstraintViolation<Object>> violations) {
        if (violations == null || violations.size() == 0) {
            return new ValidationResult(true, "");
        } else {
            String message = violations.iterator().next().getMessage();
            return new ValidationResult(false, message);
        }
    }

    private static javax.validation.Validator getValidator() {
        return Validation.buildDefaultValidatorFactory().getValidator();
    }
}
